package zhxt.helmet.utils;
import com.google.common.collect.Maps;
import org.springframework.web.socket.WebSocketSession;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;

public class WebSocketSessionManager {
    //为每个用户保存一个session. 多个摄像头线程可以共用一个session <userId, session>
    private static final BiMap<Integer, WebSocketSession> biMap = HashBiMap.create();//这里键和值是1对1的, 查一个值不会有多个键
    private static final BiMap<Integer, WebSocketSession> synchronizedBiMap = Maps.synchronizedBiMap(biMap);//包装为线程安全

    public static void addSession(int userId, WebSocketSession session) {
        synchronizedBiMap.put(userId, session);
    }

    public static void removeSession(WebSocketSession session) {
        synchronizedBiMap.inverse().remove(session);
    }

    public static WebSocketSession getSession(int userId) {
        return synchronizedBiMap.get(userId);
    }

    public static BiMap<Integer, WebSocketSession> getAllSessions() {
        return synchronizedBiMap;
    }
}